package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func main() {
	dsn := "root:root@tcp(192.168.1.11:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  true,        // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	var users []User

	db.Where("id = ?", 22).Or("name = ?", "彬少").Find(&users)
	for _, u := range users {
		fmt.Println("name:", u.Name)
	}
	//SELECT * FROM `users` WHERE id = 22 OR name = '彬少'

	// struct
	//SELECT * FROM `users` WHERE name = 'james' OR (`users`.`name` = 'john' AND `users`.`age` = 18)
	db.Where("name = 'james'").Or(User{Name: "john", Age: 18}).Find(&users)
	for _, u := range users {
		fmt.Println(u.Name)
	}

	//Map
	//SELECT * FROM `users` WHERE name = 'james' OR (`age` = 18 AND `name` = 'john')
	db.Where("name = 'james'").Or(map[string]interface{}{"name": "john", "age": 18}).Find(&users)
	for _, u := range users {
		fmt.Println(u.Name)
	}
}
